package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 添加订单
     * 1. 提交订单，要往两张表添加数据 ：  订单表(orders) 和 订单详情表(order_detail)
     * 2. 必须先往订单表里面添加记录，然后再往详情表里面添加记录
     *
     * @param orders
     * @return
     */
    @Override
    public int add(Orders orders, User user) {
        //1.订单表添加数据
        initOrders(orders, user);
        //2.订单表添加订单(数据库)
        int insert = ordersMapper.insert(orders);
        //3. 往订单详情表添加数据
        //3.1先从购物车里面拿出来数据
        List<ShoppingCart> list = shoppingCartService.selectList();
        //3.2 遍历购物车的数据，每一条购物车数据就是一个订单详情对象
        int row2 = 0;
        for (ShoppingCart shoppingCart : list) {
            //3.3 遍历一次购物车对象，就创建一个订单详情对象
            OrderDetail orderDetail = new OrderDetail();
            //3.4 把购物车条目对象拷贝到订单详情对象身上
            BeanUtils.copyProperties(shoppingCart, orderDetail, "id");
            //3.5 设置属于哪个订单
            orderDetail.setOrderId(orders.getId());
            //3.6 最后把这个订单详情对象，添加到订单详情表即可！
            row2 += orderDetailService.add(orderDetail);
        }

        //4. 如果订单都已经添加好了，那么就情况购物车
        if (insert > 0 && row2 == list.size()) {
            shoppingCartService.deleteAll();
            return 1;
        }
        //return insert >0 && row2 == list.size() ? 1 : 0;
        return 0;
    }

    /**
     * 查询订单
     *
     * @param page      页码
     * @param pageSize  条数
     * @param number    订单号
     * @param beginTime 开始日期
     * @param endTime   结束日期
     * @return
     */
    @Override
    public IPage<OrdersDto> findPage(int page, int pageSize, Long number, String beginTime, String endTime) {
        //创建分页对象
        IPage<Orders> ordersPage = new Page<>(page, pageSize);
        //构造SQL条件对象
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper();
        //判断是不是当前用户
        wrapper.eq(number != null, Orders::getNumber, number);
        //判断日期范围
        wrapper.between(beginTime != null, Orders::getOrderTime, beginTime, endTime);
        ordersMapper.selectPage(ordersPage, wrapper);


        IPage<OrdersDto> OrdersDtoPage = new Page();
        //设置 Total
        OrdersDtoPage.setTotal(ordersPage.getTotal());
        // 设置records;
        List<OrdersDto> OrdersDtoList=ordersPage.getRecords().stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            //拷贝对象
            BeanUtils.copyProperties(orders, ordersDto);
            //设置收货人信息
            ordersDto.setUserName(orders.getConsignee());
            return  ordersDto;
        }).collect(Collectors.toList());
        OrdersDtoPage.setRecords(OrdersDtoList);
        return OrdersDtoPage;

    }

    /**
     * 前端查看用户明细
     * @param pageClass
     * @param user
     * @return
     */
    @Override
    public IPage<OrdersDto> findUserPage(PageParam pageClass, User user) {
        //创建Setmeal分页对象
        IPage<Orders> ordersPage = new Page<>(pageClass.getPage(), pageClass.getPageSize());
        //构造SQL条件对象
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Orders::getUserId, user.getId());
        ordersMapper.selectPage(ordersPage, wrapper);

        IPage<OrdersDto> OrdersPage = new Page();
        //设置 Total
        OrdersPage.setTotal(ordersPage.getTotal());

        //2.2 设置records;
        List<Orders> records = ordersPage.getRecords();

        List<OrdersDto> OrdersDtoList=records.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            //获取到订单详情(菜品 价格 数量)
            List<OrderDetail> orderDetail = orderDetailService.list(orders.getId());
            ordersDto.setOrderDetails(orderDetail);
            return  ordersDto;
        }).collect(Collectors.toList());
        OrdersPage.setRecords(OrdersDtoList);
        return OrdersPage;
    }

    private void initOrders(Orders orders, User user) {
        //1.往订单表添加数据
        orders.setId(IdWorker.getId());  //雪花算法
        //1.1设置number 订单号
        orders.setNumber(orders.getId() + "");
        //1.2设置状态
        orders.setStatus(1);
        //1.3设置用户ID
        orders.setUserId(user.getId());
        //1.4设置地址
        //1.5设置提交订单时间
        orders.setOrderTime(LocalDateTime.now());
        //1.6 设置付款时间
        orders.setCheckoutTime(LocalDateTime.now());
        //1.7 设置付款方式 不需要设置，因为页面已经提供了
        //1.8 设置总金额  不需要设置，因为页面已经提供了
        //1.9 设置备注 不需要设置，因为页面已经提供了
        //1.10 提交订单的用户用户名
        orders.setUserName(user.getName());
        //1.11 收货人的电话
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        //1.12 收货人的地址 = 省份  + 城市 + 地区 + 详细地址
        orders.setAddress(
                (addressBook.getProvinceName() != null ? addressBook.getProvinceName() : "") +
                        (addressBook.getCityName() != null ? addressBook.getCityName() : "") +
                        (addressBook.getDistrictName() != null ? addressBook.getDistrictName() : "") +
                        (addressBook.getDetail() != null ? addressBook.getDetail() : "")
        );
        //1.13 收货人的名字
        orders.setConsignee(addressBook.getConsignee());
    }


}
